/*
 * Copyright (c) 2010-2015 lijunlin All Rights Reserved.
 * The software source code all copyright belongs to the author, 
 * without permission shall not be any reproduction and transmission.
 */
package org.walkerljl.boss.support.mvc.interceptor;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.walkerljl.boss.support.mvc.util.ExceptionUtils;
import org.walkerljl.boss.support.mvc.util.MvcUtils;
import org.walkerljl.commons.Constants;
import org.walkerljl.commons.util.JSONUtils;
import org.walkerljl.commons.util.MapUtils;
import org.walkerljl.commons.util.StringPool;
import org.walkerljl.commons.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * GlobalExceptionResolver
 *
 * @author lijunlin
 */
public class GlobalExceptionResolver extends SimpleMappingExceptionResolver {

    /**
     * 应用名称
     */
    private String appName;
    private String errorPage;

    /**
     * 全局异常处理
     */
    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        Boolean resource = (Boolean) request.getAttribute(Constants.STATIC_RES_REQUEST);
        if (resource != null && resource) {//静态资源
            return null;
        }
        StringBuilder messagePrefix = new StringBuilder();
        try {
            messagePrefix.append("请求:").append(request.getRequestURI()).append("");
            messagePrefix.append(", 参数:" + JSONUtils.toJSONString(request.getParameterMap()));

            ExceptionUtils.print(messagePrefix.toString(), ex);

            //发送错误邮件
            String errMessage = StringUtils.isNotBlank(ex.getMessage()) ? "操作失败:" + ex.getMessage()
                    : "系统操作失败,请联系系统维护人员";
            if (request.getRequestURI().endsWith(StringPool.JSON_SUFFIX)) {
                Map<String, Object> context = MapUtils.newHashMap();
                context.put(StringPool.RESPONSE_STATUS_KEY, false);
                context.put(StringPool.RESPONSE_MESSAGE_KEY, errMessage);
                JSONUtils.write(response.getWriter(), context, null);
            } else {
                MvcUtils.sendRedirect(errorPage);
            }
        } catch (Exception e) {
            ExceptionUtils.print(messagePrefix.toString(), e);
        }
        return null;
    }

    /**
     * 设置应用名称
     *
     * @param appName
     */
    public void setAppName(String appName) {
        this.appName = appName;
    }

    /**
     * 设置错误页面
     *
     * @param errorPage
     */
    public void setErrorPage(String errorPage) {
        this.errorPage = errorPage;
    }
}